iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 12
0

前言

解構與字串模組都是 ES6 新增加的特性,也是在撰寫 React 專案時,很常會使用到的語法,接下來就會針對解構 & 字串模組來說明如何使用。

解構的基本應用

以陣列為例子說明

在這裡將以很常見的陣列來講解解構和 rest 參數語法的基本應用,下面是幾個範例說明。

// 基本用法
[a, b] = [100, 200]; // console.log(a,b) 會得到 100 200

// 使用宣告的語法,再使用解構各別指定值
let a,b,c;
[a, b] = [5, 10, 15]; // console.log(a,b,c) 會得到 5,10,15

// 基本預設值的設定
let a, b;
[a = 15, b = 30] = [50]; // console.log(a,b) 會得到 50,30

// 交換值
const a = 20, b = 50;
[b, a] = [a, b] // console.log(a,b) 會得到 50,20

// 搭配 rest 語法
[a, b, ...rest] = [5, 10, 15, 20, 25]; // console.log(rest) 會得到 [15, 20, 25]

透過以上的範例說明,陣列實際應用起來的寫法其實很簡單,並沒有什麼很特別的語法要注意,就是使用 = (等號) 來左邊寫上宣告的變數或常數、右邊寫上要給予的數值,互相來讓右邊對應到左邊,最後當沒有對應的值時,就會得到 undefined

以物件為例子說明

在這裡將以物件來講解解構的基本應用,這裡要注意的是物件有自己的專屬符號也就是使用 ({}) 大括號來定義,下面是幾個範例說明。

// 基本用法 - 1
const { role: a } = { role: 10 } // console.log(a) 會得到 a = 10

// 基本用法 - 2
const { role: a, data: b } = { role: 20, data: 40 } // console.log(a, b) 會得到 a = 20, b = 40

// 搭配 rest 語法
const {a, b, ...rest} = {a: 2, b: 4, c: 6, d: 8} // console.log(a, b, rest) 會得到 a = 2, b = 4, rest = {c: 6, d: 8}

透過以上的範例說明,物件實際應用起來的寫法其實很簡單,只要注意好物件都是使用 ({}) 大括號且都是 key 對應 value 的關係,哪使用起來就應該也沒有多大的問題才是。

字串模組的基本應用

在 ES6 中,我們多了一個非常好用的字串模組語法,使用的情境如下:

  • 會在 JS「放入 HTML 的內容」。
  • 或者是整個要放入的字串太長而需要換行時。
  • 字串連結變數的需求。

字串模組的使用非常簡單,就是使用反引號 `(鍵盤左上角的 ~ 鍵),下面是幾個範例說明。

// 在 JS 的程式碼插入 HTML 內容,我們需要這樣寫
const cityFieldEs5 = '<div>\n' + '<ol>\n' + '<li>\n' + '</li>\n'+ '</ol>\n'+ '</div>\n'

// 上面寫的方式相當複雜且不易閱讀,如果透過 ES6 的字串模組語法,我們可以這樣寫
const cityFieldEs6 = `
<div>
  <ol>
    <li>
    </li>
  </ol>
</div>
`

// 另一個範例是在字串模組串中嵌入變數,以作者這裡最近很常接 API 的格式為範例
// Sample 1
export const fetchMasterDownloadUrl = (masterNumber, attachmentType) => (attachmentId) => () => {
  // 下載文件的 API 中,我們使用了 masterNumber、attachmentType、attachmentId 這三個變數,故也需要使用字串模組
  const url = `/documents/masters/${masterNumber}/attachments/${attachmentType}/${attachmentId}`
  return API.get(url).then((response) => {
    const { data } = response // 這個是解構的寫法
    if (data && data.errors !== undefined) {
      return Promise.reject(data.errors)
    }
    const { download_url } = data // 這個是解構的寫法
    if (!download_url) {
      return Promise.reject(translate('api.error.noDownloadUrl'))
    }
    return Promise.resolve({
      downloadUrl: download_url
    })
  }).catch(error => {
    if (!error.response || !error.response.data) { return Promise.reject(error) }
    const { errors, message } = error.response.data
    if (message) { return Promise.reject(message) }
    if (errors) { return Promise.reject(errors) }
    return Promise.reject(error)
  })
}

結論

現在是分享 ES6 心得分享,其實都是為了在準備 React 而做準備,但除了這些 ES6 的文章,整體而言還是很需要對基礎的 JavaScript 要有一定了解才行,所以一起加油吧。


上一篇
[Day - 11] JavaScript ES6 學習筆記 (一)
下一篇
[Day - 13] JavaScript ES6 學習筆記 (三)
系列文
為自己而寫,前端工程師之 30 天心得分享30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言